<template>
  <div class="app-container">
    <el-form :model="formData" size="small" :inline="true" label-width="120px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="询价单编号:" prop="enquiryCode">
            <span>{{ formData.enquiryCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="询价单名称:" prop="enquiryName">
            <span>{{ formData.enquiryName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据日期:" prop="enquiryDate">
            <span>{{ parseTime(formData.enquiryDate, '{y}-{m}-{d}') }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="询价截止时间:" prop="enquiryDeadline">
            <span>{{ parseTime(formData.enquiryDeadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="采购人:" prop="buyer">
            <span>{{ formData.buyer }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="电话:" prop="buyerPhone">
            <span>{{ formData.buyerPhone }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货地址:" prop="receivingAddress">
            <span>{{ formData.receivingAddress }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div style="font-size: 21px;">比价明细</div>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini"
                   @click="handleBatch">批量操作
        </el-button>
      </el-col>
    </el-row>

    <el-table border v-loading="loading" :data="contrastList" :span-method="objectSpanMethod" max-height="600">
      <el-table-column label="物料" align="center" width="300">
        <template slot-scope="scope">
          <p>{{scope.row.itemCode}}</p>
          <p>物料名称：{{scope.row.itemName}}</p>
          <p>规格型号：{{scope.row.specification}}</p>
          <p>单位：{{scope.row.unitOfMeasure}}</p>
        </template>
      </el-table-column>
      <el-table-column label="需求数量" align="center" prop="quantity"/>
      <el-table-column label="供应商" align="center" prop="vendorName" width="300"/>
      <el-table-column label="供货数量" align="center" prop="supplyQuantity"/>
      <el-table-column label="中标数量" align="center" prop="calibrateQuantity"width="200">
        <template slot-scope="scope">
          <el-input-number class="item__input" v-model="scope.row.calibrateQuantity" placeholder="请输入供货数量"
                           size="mini" style="width:100%"
                           :min="0"
                           :max="999999999"
                           :precision="2"
                           controls-position="right"
                           :disabled="!scope.row.isCalibrateB"
                           @change="handleEdit(scope.$index, scope.row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="含税单价" align="center" prop="taxPrice"/>
      <el-table-column label="税率" align="center" prop="tax"/>
      <el-table-column label="不含税单价" align="center" prop="noTaxPrice"/>
      <el-table-column label="含税金额" align="center" prop="taxAmount"/>
      <el-table-column label="不含税金额" align="center" prop="noTaxAmount"/>
      <el-table-column label="交货日期" align="center" prop="deliveryDate" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="定标" align="center" prop="isCalibrateB" width="50" fixed="right">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.isCalibrateB" @change="handleCheck(scope.$index, scope.row)"/>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer" style="text-align:right;margin-top: 20px;">
      <el-button type="primary" @click="saveContrast">保存并生成定标单</el-button>
      <el-button type="primary" @click="cancelContrast">返 回</el-button>
    </div>
    <!-- 定标单 -->
    <el-dialog :title="title" :visible.sync="open" width="95%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="定标单编号" prop="calibrationCode">
              <el-input v-model="form.calibrationCode" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="定标时间" prop="calibrationTime">
              <el-date-picker clearable
                              v-model="form.calibrationTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择定标时间"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="定标人" prop="calibrationUser">
              <el-input v-model="form.calibrationUser" placeholder="请选择定标人" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectUser"
                  icon="el-icon-search">
                </el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="询价单编号" prop="enquiryCode">
              <el-input v-model="form.enquiryCode" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <div style="font-size: 21px;">定标明细</div>
              </el-col>
            </el-row>
            <el-table border :data="calibrationList"  max-height="600">
              <el-table-column label="物料编号" align="center" prop="itemCode"/>
              <el-table-column label="物料名称" align="center" prop="itemName"/>
              <el-table-column label="规格型号" align="center" prop="specification"/>
              <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
              <el-table-column label="需求数量" align="center" prop="quantity"/>
              <el-table-column label="供应商" align="center" prop="vendorName" width="300"/>
              <el-table-column label="供货数量" align="center" prop="supplyQuantity"/>
              <el-table-column label="中标数量" align="center" prop="calibrateQuantity"/>
              <el-table-column label="含税单价" align="center" prop="taxPrice"/>
              <el-table-column label="税率" align="center" prop="tax"/>
              <el-table-column label="不含税单价" align="center" prop="noTaxPrice"/>
              <el-table-column label="含税金额" align="center" prop="taxAmount"/>
              <el-table-column label="不含税金额" align="center" prop="noTaxAmount"/>
              <el-table-column label="交货日期" align="center" prop="deliveryDate" width="200">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="含税金额" prop="taxAmount">
              <el-input v-model="form.taxAmount" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不含税金额" prop="noTaxAmount">
              <el-input v-model="form.noTaxAmount" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    批量操作弹框-->
    <el-dialog title="批量操作" :visible.sync="openBatch" width="500px" append-to-body>
      <el-form ref="batchForm" :model="batchForm" :rules="rules" label-width="120px">
        <el-form-item label="定标规则" prop="calibration">
          <el-radio-group v-model="batchForm.calibration" class="vertical-radio-group">
            <el-radio :label="'taxPrice'">按最低含税单价定标</el-radio>
            <el-radio :label="'noTaxPrice'">按最低不含税单价定标</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCalibration">确 定</el-button>
        <el-button @click="openBatch==false">取 消</el-button>
      </div>
    </el-dialog>
<!--    定标中等待提示-->
    <el-dialog
      :visible.sync="loadingTips"
      width="30%"
      :modal="true"
      :show-close="false"
      :close-on-click-modal="false"
      custom-class="mrp-loading-dialog"
    >
      <div class="loading-content">
        <div class="loading-spinner">
          <i class="el-icon-loading"></i>
        </div>
        <p>{{batchForm.calibration==='taxPrice'?'按最低含税单价定标':'按最低不含税单价定标'}}中，请稍等...</p >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listContrast, saveContrast} from "@/api/mes/cg/contrast";
import {addCalibration} from "@/api/mes/cg/calibration";
import UserSelect from "@/components/userSelect/single.vue";
import {getUserProfile} from "@/api/system/user";
import {genCode} from "@/api/system/autocode/rule"
export default {
  name: "Contrast",
  components: {UserSelect},
  data() {
    return {
      // 遮罩层
      loading: true,
      loadingTips:false,
      // 采购管理-采购比价明细表格数据
      contrastList: [],
      //定标单明细
      calibrationList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openBatch:false,
      // 表单参数
      form: {},
      batchForm: {},
      formData: {},
      // 表单校验
      rules: {
        calibrationCode: [
          {required: true, message: "定标单编号不能为空", trigger: "blur"}
        ],
        calibrationTime: [
          {required: true, message: "定标时间不能为空", trigger: "blur"}
        ],
        calibrationUser: [
          {required: true, message: "定标人不能为空", trigger: "blur"}
        ],
        calibration: [
          {required: true, message: "定标规则不能为空", trigger: "change"}
        ],
      },
      spanArr:[],
      user: {},
    };
  },
  created() {
    this.formData = this.$route.params;
    this.batchForm = {
      //定标规则 taxPrice-按最低含税单价定标，noTaxPrice-按最低不含税单价定标
      calibration:'taxPrice',
    }
    this.getList(this.formData.id);
    this.getUser();
  },
  methods: {
    /** 查询采购管理-采购比价明细列表 */
    getList(id) {
      this.loading = true;
      listContrast(id).then(response => {
        this.contrastList = response.data;
        // 合并单元格规则计算
        this.spanArr=[];
        let pos=0;
        this.contrastList.forEach((item, index) => {
          if(index===0){
            this.spanArr.push(1)
            pos=0
          }else{
            if(this.contrastList[index].itemId===this.contrastList[index-1].itemId){
              this.spanArr[pos] += 1
              this.spanArr.push(0)
            }else{
              this.spanArr.push(1)
              pos = index
            }
          }
        })
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelContrast(){
      this.$store.dispatch("tagsView/delView",this.$route);
      this.$router.go(-1);
    },
    // 表单重置
    reset() {
      this.calibrationList=this.contrastList.filter(item=>item.isCalibrateB===true);
      this.form = {
        id: null,
        calibrationCode:null,
        enquiryId: this.formData.id,
        enquiryCode:this.formData.enquiryCode,
        calibrationTime:this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
        calibrationUserId: this.user.userId,
        calibrationUser: this.user.nickName,
        status:'4',
        taxAmount: this.calibrationList.reduce((sum,item)=>sum+=item.taxAmount,0),
        noTaxAmount: this.calibrationList.reduce((sum,item)=>sum+=item.noTaxAmount,0),
      };
      this.resetForm("form");
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
          if (valid) {
            addCalibration(this.form).then(response => {
              this.$modal.msgSuccess("定标单生成成功");
              this.open=false;
              this.cancelContrast();
            })
          }
      })
    },
    saveContrast(){
      for (let i = 0; i <this.contrastList.length; i++) {
        const item=this.contrastList[i];
        if(item.isCalibrateB && item.calibrateQuantity<=0){
          this.$modal.msgError("请填写中标供应商的中标数量");
          return;
        }
      }
      saveContrast(this.contrastList).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("保存成功");
          //保存成功跳转生成定标单页面
          this.reset();
          this.handleAutoGenChange();
          this.title='生成定标单'
          this.open=true;
        } else {
          this.$modal.msgError(response.msg);
        }
      });
    },
    // 合并单元格方法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) { // 只在分类列合并
        const rowspan = this.spanArr[rowIndex]
        const colspan = rowspan > 0 ? 1 : 0
        return { rowspan, colspan }
      }
    },
    handleEdit(index,row){
      row.taxAmount=parseFloat((Number(row.taxPrice)*100)*(Number(row.calibrateQuantity)*100)/10000).toFixed(2);
      row.noTaxAmount=parseFloat((Number(row.noTaxPrice)*100)*(Number(row.calibrateQuantity)*100)/10000).toFixed(2);
    },
    handleCheck(index,row){
      if(!row.isCalibrateB){
        row.noTaxAmount=null;
        row.taxAmount=null;
        row.calibrateQuantity=0;
      }
    },
    handleBatch(){
      this.openBatch=true;
    },
    //批量操作确认按钮回调函数，进行自动定标操作
    handleCalibration(){
      let that=this;
      this.$refs["batchForm"].validate(valid => {
        if(valid){
          that.loadingTips=true;
          that.openBatch=false;
          //获取报价物料编号
          const uniqueCategories = that.contrastList
            .reduce((acc, curr) => {
              return acc.includes(curr.itemCode) ? acc : [...acc, curr.itemCode];
            }, []);

          //循环报价物料编码
          uniqueCategories.forEach(itemCode => {
            const itemList = that.contrastList.filter(item => item.itemCode === itemCode).sort((a, b) => a[that.batchForm.calibration] - b[that.batchForm.calibration]);
            //未定标数量
            let noCalibrateQuantity = itemList[0].quantity;
            for (const item of itemList){
              if(noCalibrateQuantity>0){
                //获取采购比价明细列表中的源对象
                const contrastItem =that.contrastList.find(contrast => contrast.itemId === item.itemId && contrast.vendorId === item.vendorId);
                const  index=that.contrastList.indexOf(contrastItem);
                //判断供应商供货数量是否大于未定标数量
                if(item.supplyQuantity>=noCalibrateQuantity){
                  const taxAmount=Number(parseFloat((Number(item.taxPrice)*10000000)*(Number(noCalibrateQuantity)*100)/1000000000).toFixed(2));
                  const noTaxAmount=Number(parseFloat((Number(item.noTaxPrice)*10000000)*(Number(noCalibrateQuantity)*100)/1000000000).toFixed(2));
                  that.contrastList.splice(index,1,
                    {...contrastItem,isCalibrateB:true,calibrateQuantity:noCalibrateQuantity,taxAmount:taxAmount,noTaxAmount:noTaxAmount});
                  break;
                }else {
                  const taxAmount=Number(parseFloat((Number(item.taxPrice)*10000000)*(Number(item.supplyQuantity)*100)/1000000000).toFixed(2));
                  const noTaxAmount=Number(parseFloat((Number(item.noTaxPrice)*10000000)*(Number(item.supplyQuantity)*100)/1000000000).toFixed(2));
                  that.contrastList.splice(index,1,{...contrastItem,isCalibrateB:true,calibrateQuantity:item.supplyQuantity,taxAmount:taxAmount,noTaxAmount:noTaxAmount});
                  noCalibrateQuantity=Number(parseFloat((Number(noCalibrateQuantity)*100-Number(item.supplyQuantity)*100)/100).toFixed(2));
                }
              }
            }
          })
          that.loadingTips=false;
        }
      })

    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.calibrationUserId = obj.userId;
        this.form.calibrationUser = obj.nickName;
      }
    },
    //自动生成编码
    handleAutoGenChange() {
      genCode('CG_CALIBRATION_CODE').then(response => {
        this.form.calibrationCode = response;
      });
    },
  }
};
</script>

<style scoped>
/* 垂直排列单选框 */
.vertical-radio-group .el-radio {
  display: block;
  margin-bottom: 10px;
}
.app-container {
  padding: 20px;
}

.mrp-loading-dialog .loading-content {
  text-align: center;
}

.mrp-loading-dialog .loading-spinner {
  font-size: 50px;
  color: #409EFF;
  margin-bottom: 10px;
}
</style>
